<!-- 单文件上传组件 -->
<template>
  <div>
    <div class="upload-demo">
      <input
        id="file"
        type="file"
        name="file"
        class="el-upload__input"
        @change="fileChange"
      >
      <div
        tabindex="0"
        class="el-upload el-upload--text"
      >
        <el-button
          size="small"
          type="primary"
          :disabled="disabled || fileList.length >= length"
          @click="btnChange"
        >
          {{ autoUpload?label:'选择文件' }}
        </el-button>
        <input
          type="file"
          name="file"
          class="el-upload__input"
          @change="fileChange"
        >
      </div>
      <div class="el-upload__tip">
        支持'RAR','html','zip','pdf','tmp','xls','xlsx','txt','ppt','doc','docx','png','jpg'等文件格式，且不超过10M
      </div>
      <ul class="el-upload-list el-upload-list--text">
        <li
          v-for="(item,index) in fileList"
          :key="index"
          tabindex="0"
          class="el-upload-list__item is-success"
        >
          <a
            class="el-upload-list__item-name"
            @click="downloadFile(item.fileName)"
          ><i class="el-icon-document" />{{ item.fileName }}</a>
          <label class="el-upload-list__item-status-label">
            <i class="el-icon-upload-success el-icon-circle-check" />
          </label>
          <i
            v-if="isDelete"
            class="el-icon-close"
            @click="handleRemove(item.fileName)"
          />
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import glob from './global.js'
import minioClient from '@/utils/minio'
import formatDate from '@/utils/date';
import { v4 as uuidv4 } from 'uuid'
export default {
  props: {
    value: {
      type: Array,
      default: () => []
    },
    isDelete: {
      type: Boolean,
      default: true
    },
    length: {
      type: Number,
      default: 5
    },
    label: {type: String, default: '上传'},//按钮文字
    accept: {String,default:'*'},//预选文件类型
    disabled: {Boolean,default:false},//预选文件类型
    autoUpload:{type:Boolean, default:true},//是否自动上传
  },
  data(){
    return {
      fileList: this.value.map(item => {
        return {
          key: item.key,
          fileName: item.fileName,
          url: item.url
        }
      })
    }
  },
  created(){
    console.log('fileList===============', this.fileList)
  },
  methods: {
    downloadFile (fileName) {
      const url = this.fileList.find(item => item.fileName === fileName).url
      window.open(url,'_self')
    },
    handleRemove (path) {
      if(this.disabled){
        return
      }
      this.fileList.splice(this.fileList.findIndex(item => item.path === path), 1)
    },
    btnChange() {
      var file = document.getElementById('file');
      file.click();
    },
    fileChange(){
      try {
        console.log('this.autoUpload:', this.autoUpload)
        const fu = this.getFile();
        if(fu==null)return;
        const checkStatus = this.beforeUpload(fu)
        if(!checkStatus){
          console.log('dddddddddddd', checkStatus)
          return;
        }
        if(this.autoUpload){
          this.submit(fu);
        }
      } catch (error) {
        console.debug('choice file err:',error);
      }
    },
    beforeUpload(f) {
      const maxSzie = glob.Config.UploadSize;
      if (f.size/1024/1024 > maxSzie) {
        this.$message.error('上传文件大小不能超过'+maxSzie+'M.');
        return false;
      }
      var types = glob.Config.UploadType;
      var arr = f.name.split('.')
      const type = arr[arr.length-1].toLowerCase();
      for (let i = 0; i < types.length; i++) {
        if(types[i].toLowerCase()==type) return true;
      }
      this.$message.error('上传文件格式不允许!');
      return false;
    },
    uploadClick(){
      this.submit();
    },
    toBuffer(ab){
      var buf = new Buffer(ab.byteLength);
      var view = new Uint8Array(ab);
      for (var i = 0; i < buf.length; ++i) {
        buf[i] = view[i];
      }
      return buf;
    },
    submit(file){
      const self = this
      try {
        if(!file) file = this.getFile();
        if(file==null)return;
        var isUpload =true;
        this.$emit('onbefore', file);
        if(!isUpload)return;
        const key = (new Date().getTime()) + '_' + Math.ceil(Math.random() * 99999)
        const reader = new FileReader()
        reader.readAsArrayBuffer(file)
        console.log('file.size:', file.size)
        reader.onload = () => {
          var metaData = {
            'Content-Type': 'application/x-png',
            'X-Amz-Meta-Testing': 1234
          }
          const prefix = formatDate(new Date(), 'yyyy-MM-dd')
          const filePath = JSON.parse(sessionStorage.getItem('user')).account + '/' + prefix + '/' + uuidv4() + '/' + file.name
          minioClient.putObject('eps', filePath, this.toBuffer(reader.result), metaData, function(err, etag) {
            if(err){
              self.$message.error('文件上传失败')
            }else{
              self.$message.success('文件上传成功')
              self.fileList.push({
                key: key,
                fileName: file.name,
                url: `${minioClient.protocol}//${minioClient.host}:${minioClient.port}/eps/${filePath}`
              })

              self.$emit('input', self.fileList);
            }
            return console.log(err, etag) // err should be null
          })
        }
      } catch (error) {
        console.debug('upload file err:',error);
      }
    },
    getFile(){
      var file = document.getElementById('file');
      if(file.files.length==0){
        this.$message.warning('没有选择文件');
        return null;
      }
      return file.files[0];
    }
  },

}
</script>
